<!-- 设备检定列表（维护列表） -->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, reactive, nextTick, watch } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { Detail, Write } from './components'
import { Dialog } from '@/components/Dialog'
import {
  busFacilityDeleteById,
  busFacilityPageDataList,
  busFacilitySaveOrUpdate,
  highwayRoadTreeList
} from '@/api/highway'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { Icon } from '@/components/Icon'
import { onlineStateOptions } from '@/assets/data/deviceData'
import { eachTree, getFirstNode } from '@/utils/tree'
import { ElTree } from 'element-plus'
import { useOtherStore } from '@/store/modules/other'

const { t } = useI18n()
const otherStore = useOtherStore()

const { tableRegister, tableState, tableMethods } = useTable({
  immediate: false,
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const treeS =
      currentNode.type === 'road' ? { roadId: unref(currentNodeKey) } : { city: currentNode.name }
    const res = await busFacilityPageDataList(
      {
        pageNum: unref(currentPage),
        pageSize: unref(pageSize)
      },
      {
        ...treeS,

        orgId: otherStore.orgId,
        ...unref(searchParams)
      }
    )
    return {
      list: res.data.records || [],
      total: res.data.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await busFacilityDeleteById({ id: unref(delId) })
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, delList } = tableMethods
const marginR = '25px'
// 设备运行监测列表:所属地市、所属路段、设备名称、设备类型、设备编号、物理位置、所属业务系统、设备IP、主DNS、运行状态、最后监测时间
// 查询:设备类型、设备名称、设备IP
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'city',
    label: '所属地市',
    search: {
      hidden: true
    }
  },
  {
    field: 'road',
    label: '所属路段',
    search: {
      hidden: true
    }
  },
  {
    field: 'pile',
    label: '所在桩号',
    search: {
      hidden: true
    }
  },
  {
    field: 'name',
    label: '设备名称'
  },
  {
    field: 'category',
    label: '设备类型'
  },
  {
    field: 'deviceNo',
    label: '设备编号',
    search: {
      hidden: true
    }
  },
  {
    field: 'physicalLocation',
    label: '物理位置',
    table: {
      slots: {
        default: () => <Icon icon="vi-ep:location-filled" class="cursor-pointer" />
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'businessSystem',
    label: '所属业务系统',
    search: {
      hidden: true
    }
  },
  {
    field: 'ip',
    label: '设备IP'
  },
  {
    field: 'primaryDns',
    label: '主DNS',
    search: {
      hidden: true
    }
  },
  {
    field: 'onlineState',
    label: '运行状态',
    table: {
      slots: {
        default: ({ row }) => {
          const value = row.onlineState
          if (value !== undefined && value !== null) {
            return <span>{onlineStateOptions[value].label}</span>
          } else {
            return <span></span>
          }
        }
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          const value = data.onlineState
          if (value !== undefined && value !== null) {
            return <span>{onlineStateOptions[value].label}</span>
          } else {
            return <span></span>
          }
        }
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'lastConnect',
    label: '最后监测时间',
    search: {
      hidden: true
    }
  },

  {
    field: 'action',
    label: t('userDemo.action'),
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 180,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <BaseButton type="primary" link onClick={() => action(row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="success" link onClick={() => action(row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton type="danger" link onClick={() => delData(row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  console.log('params', params)

  currentPage.value = 1
  if (params.createTime && params.createTime.length === 2) {
    params = { ...params, startTime: params.createTime[0], endTime: params.createTime[1] }
  }
  console.log('params', params)
  searchParams.value = params
  getList()
}

const treeEl = ref<typeof ElTree>()

const currentNodeKey = ref('')
let currentNode = reactive<any>({})

let departmentList = reactive<any[]>([])
const ElTreeProp = {
  children: 'children',
  label: 'name',
  value: 'id',
  disabled: (node) => {
    return node.type !== 'road'
  }
}
const fetchDepartment = async () => {
  const res = await highwayRoadTreeList()

  if (res.data.length === 0) return
  eachTree(res.data, (v, p) => {
    v[v.type] = v.name
    v[v.type + 'Id'] = v.id

    if (p.type) {
      v[p.type] = p.name
      v[p.type + 'Id'] = p.id
    }
    if (p.highway) {
      v.highway = p.highway
      v.highwayId = p.highwayId
    }
  })
  departmentList = res.data || []
  console.log('departmentList', departmentList)

  const nodeData: any = (res.data.length > 0 && getFirstNode(res.data)) || null
  currentNodeKey.value = nodeData.id || ''
  currentNode = nodeData
  await nextTick()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value)
  getList()
}
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.name.includes(value)
}
const currentChange = (data: any) => {
  console.log('currentChange', data)
  if (data.type === 'highway') return
  currentNodeKey.value = data.id
  currentNode = data
  currentPage.value = 1
  getList()
}

fetchDepartment()

const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = {
    orgId: otherStore.getOrgId,
    orgName: otherStore.getOrgName || '',
    city: currentNode.city,
    roadId: currentNode.type === 'road' ? currentNode.id : '',
    road: currentNode.type === 'road' ? currentNode.name : ''
  }
  console.log('AddAction', currentRow.value)
  dialogVisible.value = true
  actionType.value = ''
}

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type

  const a = {
    orgId: otherStore.getOrgId,
    orgName: otherStore.getOrgName || ''
  }
  currentRow.value = Object.assign(row, a)
  console.log('action', currentRow.value)
  dialogVisible.value = true
}

const delLoading = ref(false)

const delId = ref('')
const delData = async (row?: any) => {
  delId.value = row.id
  delLoading.value = true

  await delList(1).finally(() => {
    delLoading.value = false
  })
}
const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      console.log('保存提交', formData)
      formData.projectId = otherStore.getProjectId

      const res = await busFacilitySaveOrUpdate(formData)
      if (res) {
        currentPage.value = 1
        saveLoading.value = false
        dialogVisible.value = false
        getList()
      }
    } catch (error) {
      console.log(error)
    }
  }
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<any>()
const actionType = ref('')
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px">
      <div class="flex justify-center items-center">
        <ElInput v-model="currentDepartment" class="flex-[2]" placeholder="路段" clearable />
      </div>
      <ElDivider />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        highlight-current
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="ElTreeProp"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      />
    </ContentWrap>
    <ContentWrap class="flex-[1]">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
        :operationAdd="true"
        :operation-del="false"
        @add="AddAction"
        @batch-del="delData"
      />

      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle" width="80%" maxHeight="80vh">
      <Write
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
      />

      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
